<script lang="ts" setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useSongStoreHook } from '@/store/modules/song'
import AudioPlayer from '@/components/common/AudioPlayer/AudioPlayer.vue'

const audioPlayerRef = ref()
const songStore = useSongStoreHook()
const currentSongDetail = computed(() => songStore.currentSongDetail)
const state = computed(() => songStore.status)
const volume = computed(() => songStore.volume)
watch(
  () => volume.value,
  (newValue) => {
    audioPlayerRef.value.toggleVolume(newValue)
  }
)

onMounted(async () => {
  if (songStore.currentSongId) {
    await songStore.getSongDetail()
  }
})

// 控制按钮时间
const togglePlaying = () => {
  if (state.value) {
    audioPlayerRef.value.play()
  } else {
    audioPlayerRef.value.pause()
  }
}
const toggleSong = (type: 'pre' | 'next') => {
  songStore.toggleSong(type)
}
const ended = () => {
  // 播放完毕重置进度
  songStore.currentTime = 0
  toggleSong('next')
}
const changeState = (flag: boolean) => {
  songStore.status = flag
}
const loadedmetadata = () => {
  // 如果当前歌曲有播放进度则让其继续播放
  if (songStore.currentTime > 0) {
    audioPlayerRef.value.seek(songStore.currentTime)
  }
  // 加载音频了就让其播放
  if (!state.value) {
    audioPlayerRef.value.play()
  }
}
const timeUpdate = (e: number) => {
  songStore.currentTime = e
  localStorage.setItem('currentTime', e + '')
}

const deleteFromSonglist = () => {
  songStore.deleteSong(currentSongDetail.value)
}
</script>

<template>
  <div class="controls">
    <div class="controls_button">
      <i class="icon-liebiaoxunhuan"></i>
      <i class="icon-shangyishou" @click="toggleSong('pre')"></i>
      <i class="recommend_play" @click.stop="togglePlaying">
        <i :class="state ? 'icon-24gf-play' : 'icon-zanting'"></i>
      </i>
      <i class="icon-next" @click="toggleSong('next')"></i>
      <i class="icon-shanchu1" @click="deleteFromSonglist"></i>
    </div>
    <AudioPlayer
      ref="audioPlayerRef"
      :option="{
        src: currentSongDetail.url,
        volume
      }"
      @ended="ended"
      @play="changeState(false)"
      @pause="changeState(true)"
      @loadedmetadata="loadedmetadata"
      @timeUpdate="timeUpdate"
    />
  </div>
</template>

<style lang="scss" scoped>
.controls {
  width: 32%;
  min-width: 525px;
  .controls_button {
    margin: 8px auto 4px;
    width: 50%;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
[class*='icon'] {
  padding: 5px;
  transition: all 0.4s;
  &:hover {
    cursor: pointer;
    color: var(--music-base-color);
  }
}
.recommend_play {
  position: relative;
  background-color: var(--music-color-1);
  width: 46px;
  height: 46px;
  opacity: 1;
  box-shadow: none;
  transition: all 0.4s;
  &:hover {
    background-color: var(--music-color-2);
  }
  .icon-24gf-play,
  .icon-zanting {
    color: var(--music-icon-color);
    font-size: 20px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-48%, -50%);
  }
}
</style>
